package com.superyee.commonlib.widgets;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatDialog;

import com.superyee.commonlib.R;


/**
 * 加载等待dialog
 */

public class LoadingDialog extends AppCompatDialog {

    public static LoadingDialog createLoadingDialog(Context context, String msg) {
        LoadingDialog dialog = new LoadingDialog(context);
        dialog.show();
        dialog.setMessage(msg);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        return dialog;
    }

    public static LoadingDialog createLoadingDialog(Context context) {
        LoadingDialog loading = new LoadingDialog(context);
        loading.show();
        loading.setCancelable(false);
        loading.setCanceledOnTouchOutside(false);
        return loading;
    }

    private TextView mTvView;


    public LoadingDialog(Context context) {
        super(context, R.style.baseDialog);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.comm_layout_loading_dialog);
        mTvView = findViewById(R.id.loadingprogress_dialog_message);
    }

    public void setMessage(String message) {
        updateLoadingMessage(message);
    }

    public void setMessage(int resId) {
        updateLoadingMessage(getContext().getString(resId));
    }

    private void updateLoadingMessage(String msg) {
        mTvView.setText(msg);
        if (TextUtils.isEmpty(msg)) {
            mTvView.setVisibility(View.GONE);
        } else {
            mTvView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 关闭dialog
     * <p>
     * http://blog.csdn.net/qq_21376985
     *
     * @param mDialogUtils
     */
    public static void closeDialog(Dialog mDialogUtils) {
        if (mDialogUtils != null && mDialogUtils.isShowing()) {
            mDialogUtils.dismiss();
        }
        mDialogUtils = null;
    }

}